<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #jurisdictionCodes_Mng="{ model, field }">
        <Button>Default Button</Button>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import type { Ref } from 'vue';
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { getAllRoleList, getDeptList, getDistrictCascader } from '/@/api/demo/system';
  import {
    getDistrictList,
    editAccountList,
    addAccountList,
    isAccountExist,
  } from '/@/api/demo/system';

  import ApiCascader from '/@/components/Form/src/components/ApiCascader.vue';
  import debounce from 'lodash.debounce';
  import { encryptByMd5 } from '/@/utils/cipher';
  import { Button } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { isArray } from 'lodash-es';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm, ApiCascader, Button },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const rowName = ref('');
      const refListDist = ref([]) as Ref<any[]>;
      const userStore = useUserStore();

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        size: 'small',
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      function findAllNodes(val: any[], valOri: String[], jurisdictionCodes: String[]) {
        valOri.forEach((element) => {
          let fd = val.find((x) => x.id == element);
          if (fd) {
            if (jurisdictionCodes.indexOf(fd.regionCode) < 0) {
              jurisdictionCodes.push(fd.regionCode);
            }
            findAllNodes(val, [fd.parentId], jurisdictionCodes);
          }
        });
      }

      const AccValidator = function (_, value, _callback) {
        if (!value) {
          _callback();
          return;
        }

        isAccountExist(value)
          .then((d) => {
            if (d) {
              _callback('用户已存在');
            } else {
              _callback();
            }
          })
          .catch((err) => {
            _callback(err.message || '验证失败');
          });
      };

      function autoFillForms(roleNow, rowSub) {
        if (userStore.getUserInfo.role == roleNow) {
          const formModel = { role: rowSub };
          formModel.userGroup = userStore.getUserInfo.userGroup;
          if (userStore.getUserInfo.districtJson)
            formModel.districtCode_ = JSON.parse(userStore.getUserInfo.districtJson);

          if (userStore.getUserInfo.jurisdictionJson) {
            formModel.jurisdictionCodes_ = JSON.parse(userStore.getUserInfo.jurisdictionJson);
          }
          setFieldsValue(formModel);

          updateSchema([
            {
              field: 'role',
              show: false,
            },
          ]);
        }
      }

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          if (data.record.districtJson) {
            data.record['districtCode_'] = JSON.parse(data.record.districtJson);
          }

          if (data.record.jurisdictionJson) {
            data.record['jurisdictionCodes_'] = JSON.parse(data.record.jurisdictionJson);
          }

          updateSchema([
            {
              field: 'userName',
              dynamicDisabled: unref(isUpdate),
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                },
              ],
            },
          ]);

          rowId.value = data.record.number;
          rowName.value = data.record.uname;
          setFieldsValue({
            userName: data.record.uname,
            districtCode: data.record.district,
            ...data.record,
          });
        } else {
          updateSchema([
            {
              field: 'userName',
              dynamicDisabled: unref(isUpdate),
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                },
                {
                  validator: debounce(AccValidator, 1000),
                },
              ],
            },
          ]);

          autoFillForms('UnitAdmin', 'UnitInvestigator');
          autoFillForms('CityUnitAdmin', 'CityUnitInvestigator');
        }
        updateSchema([
          {
            field: 'pwd',
            show: !unref(isUpdate),
            required: !unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增用户3' : '编辑用户'));

      async function handleSubmit() {
        try {
          const values = await validate();

          if (isArray(values.districtCode_) && values.districtCode_.length > 0) {
            values['districtJson'] = JSON.stringify(values.districtCode_);

            const last = values.districtCode_.slice(-1)[0];
            values['districtCode'] = JSON.parse(last);
          }

          if (isArray(values.jurisdictionCodes_) && values.jurisdictionCodes_.length > 0) {
            values['jurisdictionJson'] = JSON.stringify(values.jurisdictionCodes_);

            values['jurisdictionCodes'] = [];
            const jurisdictionCodes: any[] = [];
            values.jurisdictionCodes_.forEach((element) => {
              if (isArray(element)) {
                const last = element.slice(-1)[0];
                values['jurisdictionCodes'].push(JSON.parse(last));
              } else {
                jurisdictionCodes.push(element);
              }
            });

            if (jurisdictionCodes.length > 0) {
              const last = jurisdictionCodes.slice(-1)[0];
              values['jurisdictionCodes'].push(JSON.parse(last));
            }
          }

          setModalProps({ confirmLoading: true });
          // TODO custom api
          if (unref(isUpdate)) {
            values.number = rowId.value;
            values.pwd = encryptByMd5(values.pwd);
            await editAccountList(values);
          } else {
            values.pwd = encryptByMd5(values.pwd);
            await addAccountList(values);
          }
          console.log(values);
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } catch (ex) {
          console.log(ex);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function isLeafDist(record) {
        return record.regionalLevel > 6;
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        getDistrictCascader,
        isLeafDist,
      };
    },
  });
</script>
